﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace DoNetTool.Common.Core.Util
{
    /// <summary>
    /// 图片工具类
    /// </summary>
    public class ImageUtils
    {
        /// <summary>
        /// 从大图中截取一部分图片
        /// </summary>
        /// <param name="fromImage">来源图片地址</param>        
        /// <param name="offsetX">从偏移X坐标位置开始截取</param>
        /// <param name="offsetY">从偏移Y坐标位置开始截取</param>
        /// <param name="toImagePath">保存图片地址</param>
        /// <param name="width">保存图片的宽度</param>
        /// <param name="height">保存图片的高度</param>
        /// <returns></returns>
        public static MemoryStream CaptureImage(Image fromImage, int offsetX, int offsetY, string toImagePath, int width, int height)
        {
            //原图片文件
            //创建新图位图
            Bitmap bitmap = new Bitmap(fromImage.Width, fromImage.Height);
            //创建作图区域
            Graphics graphic = Graphics.FromImage(bitmap);
            //截取原图相应区域写入作图区
            
            graphic.DrawImage(fromImage, new Rectangle(offsetX, offsetY, width, height), offsetX, offsetY, width, height, GraphicsUnit.Pixel);
            //从作图区生成新图
            Image saveImage = Image.FromHbitmap(bitmap.GetHbitmap());
            //保存图片

            MemoryStream destStream = new MemoryStream();

            if (!string.IsNullOrEmpty(toImagePath))
            {
                //fromImage.Save("D:\\Src.jpg");
                saveImage.Save(toImagePath, ImageFormat.Jpeg);
            }
            else
            {

            }
            saveImage.Save(destStream, ImageFormat.Jpeg);
            //saveImage.Save(toImagePath, ImageFormat.Jpeg);
            //saveImage.Save()
            //释放资源   
            saveImage.Dispose();
            graphic.Dispose();
            bitmap.Dispose();
            return destStream;
        }
    }
}
